# coding=utf-8
# !/usr/bin/python
import json
import os
import time
import uuid

import paramiko
from util.cnf_utils import MyCnf


class BaseSftp(object):
    def __init__(self, host, port, username, password, base_path):
        self.sftp_host = host
        self.sftp_port = int(port)
        self.username = username
        self.password = str(password)
        self.base_path = base_path


class MySftp(BaseSftp):
    # Transport对象
    __transport = None

    def __init__(self):
        self.conf = MyCnf('/cnf/my_config.cnf').get_content('sftp')
        super(MySftp, self).__init__(**self.conf)
        # 建立连接
        self._transport = self.__getTransport()
        # 创建sftp对象，SFTPClient是定义怎么传输文件、怎么交互文件
        self._sftp = paramiko.SFTPClient.from_transport(self._transport)

    def __getTransport(self):

        if MySftp.__transport is None:
            # 获取Transport实例
            __transport = paramiko.Transport((self.sftp_host, self.sftp_port))
            # 建立连接
            __transport.connect(username=self.username, password=self.password)
        return __transport

    def upload(self, local_path):
        """
        @summary: 上传图片到服务器
        @param local_path: 本地路径
        @return: json 上传结果
        """
        # 获取原文件名和后缀
        old_name = local_path[local_path.rindex('/') + 1:]
        suffix = old_name[old_name.rindex('.'): len(old_name)]
        # 文件名
        uid = str(uuid.uuid4())
        name = ''.join(uid.split('-')) + suffix
        # 文件上传目录
        remote_path = self.__getRemotePath()
        path = remote_path + '/' + name
        self._sftp.put(local_path, name)
        # 删除原图
        os.remove(local_path)
        res_path = [{
            'name': old_name,
            'path': path,
            'suffix': suffix
        }]
        return json.dumps(res_path)

    def __getRemotePath(self):
        """
        @summary: 获取日期路径
        @return: 日期路径
        """
        # 判断根目录是否存在
        try:
            self._sftp.chdir(self.base_path)
        except Exception:
            self._sftp.mkdir(self.base_path)
            self._sftp.chdir(self.base_path)
        localtime = time.localtime()
        path_list = [str(localtime.tm_year), str(localtime.tm_mon), str(localtime.tm_mday)]
        for path in path_list:
            # 当该目录存在时，进入该目录，否则创建该目录并进入该目录
            try:
                self._sftp.chdir(path)
            except Exception:
                self._sftp.mkdir(path)
                self._sftp.chdir(path)
        return self.base_path + '/'.join(path_list)

    def close(self):
        self._transport.close()


if __name__ == '__main__':
    mySftp = MySftp()
    res = mySftp.upload('/Users/liujun/Documents/tmp/b076ebbe0d3a4a649058bf4f1c144d2e..png')
    print(res)
    mySftp.close()

